package Com.Ring.TradingMobile;

import java.util.ArrayList;
import java.util.List;

import Com.Ring.TradingMobile.Lib.Common;
import Com.Ring.TradingMobile.Object.DanhMuc;
import Com.Ring.TradingMobile.SQLite.DBManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class DanhMucActivity extends ListActivity {
	
	@Override
	protected void onPause() {
		dbData.close();
		Common.StopTimer();
		Log.d(TAG, "On Pause");
		super.onPause();
	}

	@Override
	protected void onStart() {
		Runnable runable = new Common.CountDownRunner();
		Common.StartTimer(runable,DanhMucActivity.this);
		dbData = new DBManager(this);
		Refresh();
		Log.d(TAG,"On Start");
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		Log.d(TAG,"On Destroy");
		super.onDestroy();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		Log.d(TAG,"On Restart");
		super.onRestart();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		Log.d(TAG,"On Resume");
		super.onResume();
	}

	@Override
	protected void onStop() {
		Log.d(TAG, "On Stop");
		super.onStop();
	}

	StringBuilder str = new StringBuilder();

	List<String> dsXoa = new ArrayList<String>();
	private DBManager dbData;
	private Cursor CursorGlobal;

	private String[] namDM = null;
	private String DanhMucSelected = "";
	private static final String TAG = "DanhMucActivityDebug";

	private static final int THEM_DANH_MUC = 1;
	private static final int XOA_DANH_MUC = 2;
	private static final int SUA_DANH_MUC = 3;
	private static final int ENTER_SUA_DANH_MUC = 4;
	
	private Button btnBack;
	private Button btnHome;
	private Button btnRefresh;
	

	private EditText txtTenDanhMuc ;

	private static final int[] TO_DANHMUC = new int[] { R.id.itemDM };

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case THEM_DANH_MUC:
			LayoutInflater factory = LayoutInflater.from(this);
			final View themView = factory
					.inflate(R.layout.dialog_danhmuc, null);
			AlertDialog.Builder builder = new AlertDialog.Builder(
					DanhMucActivity.this);
			try {
				builder.setIcon(R.drawable.alert_dialog_icon);
				builder.setTitle(R.string.strTenDanhMuc);
				builder.setView(themView);
				builder.setPositiveButton(R.string.str_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {

								EditText txt = (EditText) themView
										.findViewById(R.id.editTenDanhMuc);
								if (!txt.getText().toString().trim().equals("")) {
									dbData.InsertDanhMuc(txt.getText().toString());
									Refresh();
									removeDialog(THEM_DANH_MUC);
								}
							}
						});

				builder.setNegativeButton(R.string.str_cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								removeDialog(THEM_DANH_MUC);
							}
						});
			} catch (Exception ex) {
				Log.d(TAG, ex.toString());
			}
			return builder.create();

		case XOA_DANH_MUC:

			AlertDialog.Builder builderXoa = new Builder(DanhMucActivity.this);
			builderXoa.setIcon(R.drawable.alert_dialog_icon);
			builderXoa.setTitle(R.string.strCofirmXoa);
			boolean[] checkedItems = null;
			final Cursor cursor = CursorGlobal;

			int count = cursor.getCount();
			if (count > 0) {
				namDM = new String[count];
				checkedItems = new boolean[count];
				cursor.moveToFirst();
				for (int i = 0; i < count; i++) {
					namDM[i] = cursor.getString(cursor
							.getColumnIndex(DanhMuc.NAME_DANH_MUC));
					checkedItems[i] = false;
					cursor.moveToNext();
				}
				cursor.moveToFirst();
			}

			builderXoa.setMultiChoiceItems(namDM, checkedItems,
					new DialogInterface.OnMultiChoiceClickListener() {
						public void onClick(DialogInterface dialog, int which,
								boolean isChecked) {
							if (dsXoa.indexOf(namDM[which]) >= 0) {
								dsXoa.remove(namDM[which]);
							} else {
								dsXoa.add(namDM[which]);
							}
						}
					});
			builderXoa.setPositiveButton(R.string.str_ok,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							if (!dsXoa.isEmpty()) {
								dbData.DeleteDanhMuc(dsXoa.toArray());
								Refresh();
								dsXoa.removeAll(dsXoa);
							}
							removeDialog(XOA_DANH_MUC);
						}
					});
			builderXoa.setNegativeButton(R.string.str_cancel,
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							if (!dsXoa.isEmpty()) {
								dsXoa.removeAll(dsXoa);
							}
							removeDialog(XOA_DANH_MUC);
						}
					});
			return builderXoa.create();
		case SUA_DANH_MUC:
			AlertDialog.Builder builderSua = new Builder(DanhMucActivity.this);
			builderSua.setIcon(R.drawable.alert_dialog_icon);
			builderSua.setTitle(R.string.strConfirmEdit);

			final Cursor cursorSua = CursorGlobal;
			builderSua.setSingleChoiceItems(cursorSua, 0,
					DanhMuc.NAME_DANH_MUC,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							cursorSua.moveToPosition(which);
							DanhMucSelected = cursorSua.getString(cursorSua
									.getColumnIndex(DanhMuc.NAME_DANH_MUC));
						}
					});
			builderSua.setPositiveButton(R.string.str_ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							if (!DanhMucSelected.equals("")) {
								showDialog(ENTER_SUA_DANH_MUC);
							}
							removeDialog(SUA_DANH_MUC);
						}
					});
			builderSua.setNegativeButton(R.string.str_cancel,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							DanhMucSelected = "";
							removeDialog(SUA_DANH_MUC);
						}
					});
			return builderSua.create();
		case ENTER_SUA_DANH_MUC:
			LayoutInflater factoryEnterSua = LayoutInflater.from(this);
			final View EnterSuaView = factoryEnterSua.inflate(
					R.layout.dialog_danhmuc, null);
			EditText txt = (EditText) EnterSuaView.findViewById(R.id.editTenDanhMuc);
			txt.setText(DanhMucSelected);
			AlertDialog.Builder builderEnterSua = new AlertDialog.Builder(
					DanhMucActivity.this);
			builderEnterSua.setIcon(R.drawable.alert_dialog_icon);
			builderEnterSua.setTitle("Sửa Danh Mục");
			builderEnterSua.setView(EnterSuaView);
			builderEnterSua.setPositiveButton(R.string.str_ok,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							EditText txt = (EditText) EnterSuaView.findViewById(R.id.editTenDanhMuc);
							String sqlExecute = String.format("update %s set %s = '%s' where %s = '%s'", DanhMuc.TABLE_NAME,DanhMuc.NAME_DANH_MUC,txt.getText().toString(),DanhMuc.NAME_DANH_MUC,DanhMucSelected);
							dbData.UpdateDanhMuc(sqlExecute);
							txt.setText("");
							Refresh();
							removeDialog(ENTER_SUA_DANH_MUC);
						}
					});

			builderEnterSua.setNegativeButton(R.string.str_cancel,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							removeDialog(ENTER_SUA_DANH_MUC);
						}
					});
			return builderEnterSua.create();
		}
		return null;
	}

	private void Refresh() {
		CursorGlobal = dbData.Select("select * from "+DanhMuc.TABLE_NAME);
		startManagingCursor(CursorGlobal);

		SimpleCursorAdapter adapter = new SimpleCursorAdapter(
				DanhMucActivity.this, R.layout.listdanhmuc, CursorGlobal,
				new String[] { DanhMuc.NAME_DANH_MUC }, TO_DANHMUC);
		adapter.notifyDataSetChanged();
		setListAdapter(adapter);

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.danhmuc);
		
		Log.d(TAG,"On Create");
		Button btnThemDanhMuc = (Button) findViewById(R.id.btnThemDanhMuc);
		Button btnXoaDanhMuc = (Button) findViewById(R.id.btnXoaDanhMuc);
		Button btnSuaDanhMuc = (Button) findViewById(R.id.btnSuaDanhMuc);
		txtTenDanhMuc = (EditText)findViewById(R.id.txtTenDanhMuc);
		btnThemDanhMuc.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String txtTen = txtTenDanhMuc.getText().toString().trim();
				if(!txtTen.equals("")) {
					dbData.InsertDanhMuc(txtTen);
					Refresh();
					txtTenDanhMuc.setText("");
				}
				//showDialog(THEM_DANH_MUC);
			}
		});

		btnXoaDanhMuc.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showDialog(XOA_DANH_MUC);
			}
		});

		btnSuaDanhMuc.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showDialog(SUA_DANH_MUC);
			}
		});
		
		btnBack = (Button)findViewById(R.id.btnBack);
		btnHome = (Button)findViewById(R.id.btnHome);
		btnRefresh = (Button)findViewById(R.id.btnRefresh);
		
		btnBack.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(),
						TradingMobileActivity.class);
				startActivity(intent);
				finish();
			}
		});
		
		btnHome.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(v.getContext(),
						TradingMobileActivity.class);
				startActivity(intent);
				finish();
			}
		});
		
		
		btnRefresh.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Refresh();
			}
		});
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView,
	 * android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		TextView txt = (TextView)v;
		Intent intent = new Intent(v.getContext(),
				ThiTruongActivity.class);
		Bundle senderBundle = new Bundle();
		senderBundle.putStringArray(Common.KeyIntentThiTruong,
				new String[]{"1", txt.getText().toString(),"1"});
		intent.putExtras(senderBundle);
		startActivity(intent);
	}
}
